// pages/form/index.js
const app=getApp();
const keys=['channel','concatAccess','caseType','caseCategory','resourceType','resourceLevel'];
let dictCache={};
Page({
  editorCtx:null,
  data: {
    id:0,
    channelObjs: [],
    channelMap:{},
    channels: [],
    channelIndex: 0,
    channelValue:'',
    channelAccount: '',
    nickName: '',
    sourceObjs: [],
    sourceMap:{},
    sources: ['来源1', '来源2', '来源3'],
    sourceIndex: 0,
    sourceValue:'',
    phone: '',
    wechat: '',
    caseCategoryObjs:[],
    caseCategoryMap:{},
    caseCategories: ['A','B','D','F'],
    caseCategoryIndex:0,
    caseCategoryValue:'',
    allCaseTypeObjs:[],
    caseTypeObjs:[],
    caseTypeMap:{},
    caseTypes: ['类型1', '类型2', '类型3'],
    caseTypeIndex: 0,
    caseTypeValue:'',
    remark: '',
    editorReady:false
  },

  // 渠道选择
  bindChannelChange(e) {
    this.setData({ channelIndex: e.detail.value ,channelValue:this.data.channels[e.detail.value]});
  },

  // 渠道账号输入
  onChannelAccountInput(e) {
    this.setData({ channelAccount: e.detail.value });
  },

  // 客户昵称输入
  onClientNicknameInput(e) {
    this.setData({ nickName: e.detail.value });
  },

  // 来源方式选择
  bindSourceChange(e) {
    this.setData({ sourceIndex: e.detail.value,sourceValue: this.data.sources[ e.detail.value] });
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  // 微信输入
  onWechatInput(e) {
    this.setData({ wechat: e.detail.value });
  },

  // 案件大类选择
  bindCaseCategoryChange(e) {
    const allCaseTypeObjs=this.data.allCaseTypeObjs;
    const caseCategoryValue=this.data.caseCategoryObjs[e.detail.value].value;
    const caseTypeObjs= allCaseTypeObjs
    .filter(p=>p.value.startsWith(caseCategoryValue));
    const caseTypes= caseTypeObjs.map(p=>p.label);
    this.setData({ caseCategoryIndex: e.detail.value ,caseCategoryValue:caseCategoryValue
      ,caseTypeObjs: caseTypeObjs
      ,caseTypes:caseTypes,caseTypeValue:'',caseTypeIndex:0});
  },
 
  // 案件类型选择
  bindCaseTypeChange(e) {
    this.setData({ caseTypeIndex: e.detail.value,caseTypeValue:this.data.caseTypes[e.detail.value] });
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },

  // 提交表单
  submitForm() {
    const formData = {
      id: this.data.id,
      channel: this.data.channelObjs[this.data.channelIndex].value,
      channelAccount: this.data.channelAccount,
      nickName: this.data.nickName,
      concatAccess: this.data.sourceObjs[this.data.sourceIndex].value,
      phone: this.data.phone,
      wechat: this.data.wechat,
      caseCategory: this.data.caseCategoryObjs[this.data.caseCategoryIndex].value,
      caseType: this.data.caseTypeObjs[this.data.caseTypeIndex].value,
      content: this.data.remark
    };

    console.log('提交数据:', formData);
    // 这里可以调用 API 提交数据
    this.update(formData,(data)=>{
      wx.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 2000
      });
    });
  },
 

// 修改 onShow 方法
onShow: async function () {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  console.log("进入详情页面!", options);
  
  try {
    // 1. 加载字典
    const dictMap = await this.loadDictCached(keys);
    this.initPage(dictMap);
    
    // 2. 加载详情
    if (options.id !== this.data.id) {
      this.setData({ id: options.id });
      const data = await this.fetchData(options.id);
      console.log('加载详情完成!id:', options.id, data);
      
      // 延迟执行，确保 editor 已初始化
      setTimeout(() => {
        if (this.data.editorReady && this.editorCtx) {
          this.fillData(data);
        } else {
          console.error("富文本未初始化成功");
        }
      }, 500);
    }
  } catch (error) {
    console.error('页面加载失败:', error);
  }
},

  initPage:function(dictMap){
    const channelDictItems=dictMap['channel'];
    const channels= channelDictItems.map((v)=> v.label);
    const channelMap=app.util.toMap(channelDictItems,(channel)=>channel.value);
 
    const sourceObjs=dictMap['concatAccess'];
    const sources= sourceObjs.map((v)=> v.label);
    const sourceMap=app.util.toMap(sourceObjs,(s)=>s.value);

    const caseCategoryObjs=dictMap['caseCategory'];
    const caseCategoryMap=app.util.toMap(caseCategoryObjs,(s)=>s.value);
    const caseCategories= caseCategoryObjs.map((v)=> v.label);
    const allCaseTypeObjs=dictMap['caseType'];
    const caseTypeMap=app.util.toMap(allCaseTypeObjs,(s)=>s.value);

    this.setData({channelObjs:channelDictItems,channels:channels,channelMap:channelMap
                ,sourceObjs:sourceObjs,sources:sources,sourceMap:sourceMap
                ,caseCategoryObjs:caseCategoryObjs,caseCategories:caseCategories,caseCategoryMap:caseCategoryMap
                ,allCaseTypeObjs:allCaseTypeObjs,caseTypeMap:caseTypeMap});
  },
  fillData:function(data){
    if(!data)
      return;
    const channelValue=data.channelTitle || this.data.channelMap[data.channel].label;
    const caseCategoryValue= data.caseCategoryTitle || this.data.caseCategoryMap[data.caseCategory].label;
    const caseTypeValue=data.caseTypeTitle || this.data.caseTypeMap[data.caseType].label;
    const concatAccessValue= data.concatAccessTitle || this.data.sourceMap[data.concatAccess].label;
    const phone = app.decryptData(data.phone);
    const wechat = app.decryptData(data.wechat);
    let content=data.content;
    if(content.includes("<img src=\"../files")){
      content = content.replaceAll("<img src=\"../files","<img src=\"http://121.43.62.1:8080/manager/files");
      console.log("修改前的内容:",data.content);
      console.log("修改后的内容:", content);
    }
    this.setData({channelValue:channelValue
                ,caseCategoryValue:caseCategoryValue
                ,caseTypeValue:caseTypeValue
                ,sourceValue:concatAccessValue,
                nickName:data.nickName,wechat:wechat,phone:phone,channelAccount:data.channelAccount,remark:content});
    this.setContent(content);
  },
  // fetchData 返回 Promise
fetchData(id) {
  return new Promise((resolve, reject) => {
    app.request.get(`/customer?id=${id}`, (res) => {
      if (res.code === 0) {
        resolve(res.data);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        reject(new Error(res.msg));
      }
    }, (err) => {
      wx.showToast({ title: '网络连接失败', icon: 'none' });
      reject(err);
    });
  });
},

// ✅ 带缓存的 loadDict
loadDictCached:function(keys) {
  const cacheKey = keys.sort().join(','); // 用 keys 排序后作为缓存 key

  // 1. 如果已缓存，直接返回
  if (dictCache[cacheKey]) {
    return Promise.resolve(dictCache[cacheKey]);
  }

  // 3. 第一次加载，发起请求
  const promise = new Promise((resolve, reject) => {
    app.request.post('/sysDict/loadByKeys', [...keys], (res) => {
      if (res.code === 0) {
        dictCache[cacheKey] = res.data; // ✅ 缓存数据
        resolve(res.data);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        reject(new Error(res.msg));
      }
    }, (err) => {
      wx.showToast({ title: '网络连接失败', icon: 'none' });
      reject(err);
    });
  });

  return promise;
},
 // loadDict 返回 Promise
loadDict(keys) {
  return new Promise((resolve, reject) => {
    app.request.post('/sysDict/loadByKeys', [...keys], (res) => {
      if (res.code === 0) {
        resolve(res.data);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        reject(new Error(res.msg));
      }
    }, (err) => {
      wx.showToast({ title: '网络连接失败', icon: 'none' });
      reject(err);
    });
  });
},
  
  update:function(payload,callback){
     
    app.request.put('/customer', payload, (res) => {
      console.log('保存数据返回:', res);
      if(res.code ===0){
        // 这里设置data里这个枚举的数组
        callback(res.data);
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        });
      }     
    },(err)=>{
      wx.showToast({
        title: '网络连接失败',
        icon: 'none',
        duration: 2000
      });
    });
  },
  


  undo() {
    this.editorCtx.undo();
  },
  redo() {
    this.editorCtx.redo();
  },
  //分割线
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    });
  },
  // 移除样式
  removeFormat() {
    this.editorCtx.removeFormat();
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },

  // onEditorReady: function(e) {
  //   // 检查 ctx 是否存在
  //   console.log("editor初始化完成1",e);
  //   if (e.detail && e.detail.ctx) {
  //     this.editorCtx = e.detail.ctx;
  //     this.setData({
  //       editorReady: true
  //     });
  //     console.log("editor初始化完成2", this.editorCtx, this.data.editorReady);
  //   } else {
  //     console.error("editor初始化失败2，ctx为undefined");
  //   }
  // },
  onEditorReady:function(e) {
   
    this.setData({
      editorReady: true
    });
    console.log("editor初始化完成1",this.editorCtx,this.data.editorReady);
     const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      console.log("editor初始化完成2",res);

      /*注释部分为获取上一页的富文本字符串到本页，通过setContents初始化编辑器内容 */
      // let pages = getCurrentPages()
      // let pre = pages[pages.length - 2]
      // let {
      //   ofunction
      // } = pre.data
      // console.log(recruitinfo);
      // if (!recruitinfo.ofunction) {
      //   return
      // }
      // that.editorCtx.setContents({
      //   html: ofunction
      // })

    }).exec()
   },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    console.log(e);
    console.log('format', name, value)
    if (!name) return
    this.editorCtx.format(name, value)

  },
  geteditcontent:async function () {
    return new Promise((resolve, reject) => {
      this.editorCtx.getContents({
        success: ({
          html,
          text,
          delta
        }) => {
          console.log(html, 'success');
          resolve(html);         
        },
        fail: error => {
          console.log(error);
          reject(error);
        }
      })
    })
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
    console.log(e);
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        /* 一下注释部分为上传到服务器并将的服务器图片真实地址存放到富文本中*/
        const uploadUrl= app.baseUrl+'/sysFiles/upload';
        console.log("开始上传文件到服务器",app.request.host, uploadUrl, res.tempFilePaths[0]);
        wx.uploadFile({
          url: uploadUrl, // 服务器上传图片地址
          filePath: res.tempFilePaths[0],
          header: {
            "Content-Type": "multipart/form-data"
          },
          name: 'file',
          formData: { 
            name: 'file'
          },
          success: (ress) => {
            // this.setData({})}
            console.log('图片上传结果返回', ress);
            if(ress.statusCode===200 && ress.data){
              const respBody= app.util.parseJsonObject(ress.data);
              if(respBody.code===0){
                console.log('上传后的图片地址:',respBody.data);
                that.editorCtx.insertImage({
                   src: respBody.data,  
                   width: '80%',
                  success: function () {
                    console.log('insert image success')
                  }
                })
              }
            }
          }
        })
      }
    })
  },
  setContent: function(content) {
    const that = this;
    that.setData({ remark: content });
    console.log("要反显的内容",content);
    if (!that.editorCtx || !content) return;
    
    // 尝试多次设置内容
    let attempts = 0;
    const maxAttempts = 3;
    
    const trySetContent = () => {
      attempts++;
      that.editorCtx.setContents({
        html: content,
        success: () => {
          console.log('反显成功');
        },
        fail: (err) => {
          if (attempts < maxAttempts) {
            setTimeout(trySetContent, 500);
          } else {
            console.error('反显失败', err);
            wx.showToast({
              title: '反显失败',
              icon: 'none'
            });
          }
        }
      });
    };
    trySetContent();
  }
});
